/*
 * To change this license header, choose License Headers in Project Properties.
 */
package dreamwar.view;

import dreamwar.controller.GUIController;
import dreamwar.model.PersistenceProperties;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;

/**
 * A <code>JFrame</code> that shows fields to connect to a data base.
 * <p>
 * Can use it to connect any MySQL database server. If you let the fields empty
 * it takes default values.
 * <p>
 * The Connect button try to open the connection and, if succeed, open a new
 * <code>JFrame</code>.
 * <p>
 * <b>Warning:</b> Will need a <code>GUIController</code> to work.
 *
 * @author Berto_Romero
 * @version %I%, %G%
 */
public class LoginFrame extends javax.swing.JFrame {

    /**
     * Creates new form LoginJFrame
     */
    public LoginFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        mainScrollPane = new javax.swing.JScrollPane();
        mainPanel = new javax.swing.JPanel();
        ipAddressLabel = new javax.swing.JLabel();
        ipAddressTextField = new javax.swing.JTextField();
        portLabel = new javax.swing.JLabel();
        portTextField = new javax.swing.JTextField();
        userNameLabel = new javax.swing.JLabel();
        userNameTextField = new javax.swing.JTextField();
        passwordLabel = new javax.swing.JLabel();
        passwordField = new javax.swing.JPasswordField();
        keypadPanel = new javax.swing.JPanel();
        connectButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(400, 300));
        getContentPane().setLayout(new java.awt.GridLayout(1, 0));

        mainScrollPane.setPreferredSize(new java.awt.Dimension(350, 200));

        mainPanel.setPreferredSize(new java.awt.Dimension(350, 200));
        java.awt.GridBagLayout jPanel1Layout = new java.awt.GridBagLayout();
        jPanel1Layout.columnWidths = new int[] {0, 5, 0, 5, 0, 5, 0};
        jPanel1Layout.rowHeights = new int[] {0, 7, 0, 7, 0, 7, 0};
        mainPanel.setLayout(jPanel1Layout);

        ipAddressLabel.setText("URL o IP");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        mainPanel.add(ipAddressLabel, gridBagConstraints);

        ipAddressTextField.setText("localhost");
        ipAddressTextField.setPreferredSize(new java.awt.Dimension(150, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        mainPanel.add(ipAddressTextField, gridBagConstraints);

        portLabel.setText("Puerto");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        mainPanel.add(portLabel, gridBagConstraints);

        portTextField.setText("3306");
        portTextField.setPreferredSize(new java.awt.Dimension(38, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 6;
        gridBagConstraints.gridy = 0;
        mainPanel.add(portTextField, gridBagConstraints);

        userNameLabel.setText("Usuario");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        mainPanel.add(userNameLabel, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 5;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        mainPanel.add(userNameTextField, gridBagConstraints);

        passwordLabel.setText("Contraseña");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        mainPanel.add(passwordLabel, gridBagConstraints);

        passwordField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                passwordFieldActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridwidth = 5;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        mainPanel.add(passwordField, gridBagConstraints);

        keypadPanel.setLayout(new java.awt.GridLayout(1, 0, 5, 0));

        connectButton.setText("Conectar");
        connectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectButtonActionPerformed(evt);
            }
        });
        keypadPanel.add(connectButton);

        exitButton.setText("Salir");
        exitButton.setMaximumSize(new java.awt.Dimension(77, 23));
        exitButton.setMinimumSize(new java.awt.Dimension(77, 23));
        exitButton.setPreferredSize(new java.awt.Dimension(77, 23));
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });
        keypadPanel.add(exitButton);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 6;
        gridBagConstraints.gridwidth = 7;
        mainPanel.add(keypadPanel, gridBagConstraints);

        mainScrollPane.setViewportView(mainPanel);

        getContentPane().add(mainScrollPane);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_exitButtonActionPerformed

    private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed
        validateConnection();
    }//GEN-LAST:event_connectButtonActionPerformed

    private void passwordFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_passwordFieldActionPerformed
        validateConnection();
    }//GEN-LAST:event_passwordFieldActionPerformed

    /**
     * Checks the connection and opens the new frame if validates. If can
     * connect to the data base closes this frame and opens a new frame with the
     * main content.
     * <p>
     * If it cannot, throws a message with the connection error.
     */
    private void validateConnection() {
        Map<String, String> customPersistencePropertiesValues = getCustomPersistencePropertiesValues();
        if (connect(customPersistencePropertiesValues)) {
            this.setVisible(false);
            this.dispose();
            GUIController.getInstance().showMainFrame();
        } else {
            JOptionPane.showMessageDialog(this, "<html><body><p style='width: 300px;'>Se ha producido un error al intentar conectarse con la base de datos. Alguno de los campos pueden ser erroneos.<br /><br /> Si el problema persiste inténtelo de nuevo más tarde o contacte con el administrador</p></body></html>", "Error al intentar conectar", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * Sets the new properties for the connection and tries to connect.
     *
     * @param customPersistencePropertiesValues The map with the new values to
     * set up the DriverManager connection.
     * @return <code>true</code> if the connection is ready; <code>false</code>
     * if cannot connect.
     */
    private boolean connect(Map<String, String> customPersistencePropertiesValues) {
        PersistenceProperties persistenceProperties = PersistenceProperties.getInstance(customPersistencePropertiesValues);
        return persistenceProperties.isReady();
    }

    /**
     * Maps the property values from the information set. Get the values from
     * the correspondent fields:
     * <ul>
     * <li>The user name. Default: root.
     * <li>The user password. Default: root.
     * <li>The ip address or the url. Default: localhost.
     * <li>The connection port. Default: 3306.
     * </ul>
     * <p>
     * If any value is empty, sets the default value.
     *
     * @return The mapped property connection values.
     */
    private Map<String, String> getCustomPersistencePropertiesValues() {
        Map<String, String> customPersistencePropertiesValues = new HashMap<>();
        customPersistencePropertiesValues.put("user", userNameTextField.getText().isEmpty() ? "root" : userNameTextField.getText().trim());
        customPersistencePropertiesValues.put("password", String.valueOf(passwordField.getPassword()).isEmpty() ? "root" : String.valueOf(passwordField.getPassword()).trim());
        customPersistencePropertiesValues.put("ipAddress", ipAddressTextField.getText().isEmpty() ? "localhost" : ipAddressTextField.getText().trim());
        customPersistencePropertiesValues.put("port", portTextField.getText().isEmpty() ? "3306" : portTextField.getText().trim());
        return customPersistencePropertiesValues;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Windows look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Windows (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                LoginFrame loginFrame = new LoginFrame();
                GUIController.getInstance().setLoginFrame(loginFrame);
                loginFrame.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton connectButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JLabel ipAddressLabel;
    private javax.swing.JTextField ipAddressTextField;
    private javax.swing.JPanel keypadPanel;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JScrollPane mainScrollPane;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JLabel portLabel;
    private javax.swing.JTextField portTextField;
    private javax.swing.JLabel userNameLabel;
    private javax.swing.JTextField userNameTextField;
    // End of variables declaration//GEN-END:variables
}
